#!/usr/bin/env nu
# Info: Script to run Provisioning Workflow Management
# Author: JesusPerezLorenzo
# Release: 1.0.0
# Date: 29-09-2025

use std log

use lib_provisioning *
use env.nu *
use ../workflows/management.nu *

# - > Help on Workflow
export def "main help" [
  --src: string = ""
  --notitles       # not titles
  --out: string    # Print Output format: json, yaml, text (default)
]: nothing -> nothing {
  if $notitles == null or not $notitles { show_titles }
  ^$"($env.PROVISIONING_NAME)" -mod workflow --help
  if ($out | is-not-empty) { $env.PROVISIONING_NO_TERMINAL = false }
  print (provisioning_options $src)
  if not $env.PROVISIONING_DEBUG { end_run "" }
}

# > Workflow Management and Orchestration
def main [
  ...args: string  # Other options, use help to get info
  -v               # Show version
  -i               # Show Info
  --version (-V)   # Show version with title
  --info (-I)      # Show Info with title
  --about (-a)     # Show About
  --task-id: string  # Workflow task ID
  --status: string  # Filter by status: Pending, Running, Completed, Failed, Cancelled
  --orchestrator: string = "http://localhost:8080"  # Orchestrator URL
  --interval: int = 3  # Monitoring interval in seconds
  --days: int = 7  # Cleanup days threshold
  --dry-run        # Show what would be done without doing it
  --format: string  # Output format: table, json, yaml
  --check (-c)     # Only check mode, no actual changes
  --yes (-y)       # Confirm task
  --debug (-x)     # Use Debug mode
  --xm             # Debug with PROVISIONING_METADATA
  --xld            # Log level with DEBUG PROVISIONING_LOG_LEVEL=debug
  --metadata       # Error with metadata (-xm)
  --notitles       # Do not show banner titles
  --helpinfo (-h)  # For more details use options "help" (no dashes)
  --out: string    # Print Output format: json, yaml, text (default)
]: nothing -> nothing {
  if ($out | is-not-empty) {
    $env.PROVISIONING_OUT = $out
    $env.PROVISIONING_NO_TERMINAL = true
  }
  provisioning_init $helpinfo "workflow" $args
  if $version or $v { ^$env.PROVISIONING_NAME -v ; exit }
  if $info or $i { ^$env.PROVISIONING_NAME -i ; exit }
  if $about {
    _print (get_about_info)
    exit
  }
  if $debug { $env.PROVISIONING_DEBUG = true }
  if $metadata { $env.PROVISIONING_METADATA = true }

  let task = if ($args | length) > 0 { ($args | get 0) } else { "" }
  let ops = $"($env.PROVISIONING_ARGS? | default "") " | str replace $" ($task) " "" | str trim
  let workflow_file = if ($ops | is-not-empty) and not ($ops | str starts-with "-") {
    ($ops | split row " " | get 0)
  } else {
    ""
  }

  $env.PROVISIONING_MODULE = "workflow"

  let output_format = if ($format | is-not-empty) {
    $format
  } else if ($out | is-not-empty) {
    $out
  } else {
    "table"
  }

  match $task {
    "h" | "help" => {
      # Redirect to main categorized help system
      exec $"($env.PROVISIONING_NAME)" help orchestration --notitles
    },
    "list" => {
      let result = if ($status | is-not-empty) {
        workflow list --orchestrator $orchestrator --status $status
      } else {
        workflow list --orchestrator $orchestrator
      }

      if ($output_format | is-not-empty) {
        if $output_format == "json" {
          print ($result | to json)
        } else if $output_format == "yaml" {
          print ($result | to yaml)
        } else {
          print ($result | table)
        }
      } else {
        print ($result | table)
      }
    },
    "status" => {
      if ($task_id | is-empty) and ($workflow_file | is-empty) {
        print "❌ Please provide a task ID using --task-id or as argument"
        exit 1
      }
      let tid = if ($task_id | is-not-empty) { $task_id } else { $workflow_file }
      let result = workflow status $tid --orchestrator $orchestrator

      if ($output_format | is-not-empty) {
        if $output_format == "json" {
          print ($result | to json)
        } else if $output_format == "yaml" {
          print ($result | to yaml)
        } else {
          print ($result | table)
        }
      } else {
        print "📊 Workflow Status"
        print "═════════════════"
        print $result
      }
    },
    "monitor" => {
      if ($task_id | is-empty) and ($workflow_file | is-empty) {
        print "❌ Please provide a task ID using --task-id or as argument"
        exit 1
      }
      let tid = if ($task_id | is-not-empty) { $task_id } else { $workflow_file }
      workflow monitor $tid --orchestrator $orchestrator
    },
    "stats" => {
      let result = workflow stats --orchestrator $orchestrator

      if ($output_format | is-not-empty) {
        if $output_format == "json" {
          print ($result | to json)
        } else if $output_format == "yaml" {
          print ($result | to yaml)
        } else {
          print ($result | table)
        }
      } else {
        print "📊 Workflow Statistics"
        print "═════════════════════"
        print $"Total Workflows: ($result.total)"
        print $"  ✅ Completed: ($result.completed)"
        print $"  ❌ Failed: ($result.failed)"
        print $"  🔄 Running: ($result.running)"
        print $"  ⏳ Pending: ($result.pending)"
        print $"  🚫 Cancelled: ($result.cancelled)"
        print $"  📈 Success Rate: ($result.success_rate)%"
      }
    },
    "cleanup" => {
      if $dry_run {
        workflow cleanup --orchestrator $orchestrator --days $days --dry-run
      } else {
        if not $yes {
          print $"⚠️  This will clean up workflows older than ($days) days. Use --yes to confirm."
          exit 1
        }
        workflow cleanup --orchestrator $orchestrator --days $days
      }
    },
    "orchestrator" => {
      let result = workflow orchestrator --orchestrator $orchestrator

      if ($output_format | is-not-empty) {
        if $output_format == "json" {
          print ($result | to json)
        } else if $output_format == "yaml" {
          print ($result | to yaml)
        } else {
          print ($result | table)
        }
      } else {
        print "🔧 Orchestrator Health"
        print "═════════════════════"
        print $"Status: ($result.status)"
        print $"Message: ($result.message)"
        print $"URL: ($result.orchestrator_url)"
        if ($result | get -o workflow_stats | is-not-empty) {
          print ""
          print "Workflow Statistics:"
          let stats = ($result | get workflow_stats)
          print $"  Total: ($stats.total)"
          print $"  Completed: ($stats.completed)"
          print $"  Running: ($stats.running)"
        }
      }
    },
    "submit" => {
      if ($workflow_file | is-empty) {
        print "❌ Please provide a workflow file path as argument"
        exit 1
      }

      if not ($workflow_file | path exists) {
        print $"❌ Workflow file not found: ($workflow_file)"
        exit 1
      }

      print $"📤 Submitting workflow from file: ($workflow_file)"
      print "Note: Submit requires workflow type, operation, and target parameters"
      print "Please use the specific workflow commands for now:"
      print "  - Server workflows: provisioning/core/cli/provisioning server create --orchestrated"
      print "  - Taskserv workflows: nu -c 'use core/nulib/workflows/taskserv.nu *; taskserv create <name> <infra>'"
      print "  - Cluster workflows: nu -c 'use core/nulib/workflows/cluster.nu *; cluster create <name> <infra>'"
    },
    _ => {
      print $"❌ Unknown task: ($task)"
      print "Use 'provisioning workflow help' for available commands"
      print ""
      print "Available commands:"
      print "  list [--status <status>] - List all workflows"
      print "  status <task_id> - Get workflow status"
      print "  monitor <task_id> - Monitor workflow in real-time"
      print "  stats - Show workflow statistics"
      print "  cleanup [--days 7] [--dry-run] - Clean up old workflows"
      print "  orchestrator - Check orchestrator health"
      print "  submit <file> - Submit workflow (coming soon)"
      exit 1
    }
  }
}